// import { legacy_createStore as createStore } from 'redux'
import {
  configureStore, // 用于创建仓库
  createSlice, // 创建切片
  createSelector, // 创建选择器
} from './@reduxjs/toolkit'
import logger from 'redux-logger'

const counter1Slice = createSlice({
  name: "counter1",
  initialState: { number: 0 },
  reducers: {
    add: state => {
      state.number = state.number + 1
    },
    minus: (state, action) => {
      state.number = state.number - action.payload
    }
  }
})
const {
  add: add1,
  minus: minus1,
} = counter1Slice.actions
console.log('counter1Slice', counter1Slice)
console.log('add1的返回值', add1())

const counter2Slice = createSlice({
  name: "counter2",
  initialState: { number: 0 },
  reducers: {
    add: state => {
      state.number = state.number + 1
    },
    minus: (state, action) => {
      state.number = state.number - action.payload
    }
  }
})
const {
  add: add2,
  minus: minus2,
} = counter2Slice.actions
// const store = createStore(reducer)
const store = configureStore({
  reducer: {
    [counter1Slice.reducerPath]: counter1Slice.reducer,
    [counter2Slice.reducerPath]: counter2Slice.reducer,
  },
  middleware: defaultMiddlewares => [...defaultMiddlewares(), logger], // 合并内置中间件
  preloadedState: {
    [counter1Slice.reducerPath]: { number: 0 },
    [counter2Slice.reducerPath]: { number: 0 }
  },
})

let valueEl1 = document.getElementById('value1')
function render1() {
  valueEl1.innerHTML = `value1 - ` + store.getState().counter1.number
}
render1()

store.subscribe(render1)
let valueEl2 = document.getElementById('value2')
function render2() {
  valueEl2.innerHTML = `value2 - ` + store.getState().counter2.number
}
render2()

store.subscribe(render2)

// 获取一个记忆函数
const sumSelector = createSelector(
  [state => state.counter1, state => state.counter2],
  (counter1, counter2) => {
    console.log('计算 sum')
    return counter1.number + counter2.number
  })
const sumEl = document.getElementById('sum')
function renderSUM() {
  sumEl.innerHTML = sumSelector(store.getState())
}
renderSUM()
store.subscribe(renderSUM)



document.getElementById('add1').addEventListener('click', () => store.dispatch(add1()))

document.getElementById('minus1').addEventListener('click', () => store.dispatch(minus1(0)))

document.getElementById('add2').addEventListener('click', () => store.dispatch(add2()))

document.getElementById('minus2').addEventListener('click', () => store.dispatch(minus2(2)))

